package org.youyun56.gpsserver.common;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FolderUtils {

	public static List<String> findFolders(String folder) {
		File file = new File(folder);
		if (!file.exists()) {
			return null;
		}
		if (!file.isDirectory()) {
			return null;
		}
		ArrayList<String> list = new ArrayList<String>();
		File[] files = file.listFiles();
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				if (files[i].isDirectory()) {
					list.add(files[i].getName());
				}
			}
		}
		return list;
	}


	public static List<String> findFiles(String folder) {
		File file = new File(folder);
		if (!file.exists()) {
			return null;
		}
		if (!file.isDirectory()) {
			return null;
		}
		ArrayList<String> list = new ArrayList<String>();
		File[] files = file.listFiles();
		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				if (files[i].isFile()) {
					list.add(files[i].getName());
				}
			}
		}
		return list;
	}

	public static List<String> findFiles(String folder, String regexp) {
		List<String> list = findFiles(folder);
		if (list == null) {
			return null;
		}
		for (int i = list.size() - 1; i >= 0; i--) {
			String filename = list.get(i);
			Pattern pattern = Pattern.compile(regexp);
			Matcher matcher = pattern.matcher(filename);
			boolean matched = matcher.matches();
			if (!matched) {
				list.remove(i);
			}
		}
		return list;
	}

	public static List<String> findFilesWithSubFolders(String folder, String regexp) {
		List<String> list = new ArrayList<String>();
		File file = new File(folder);
		File[] files = file.listFiles();
		if (files != null && files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				File f = files[i];
				final String absolutePath = f.getAbsolutePath();
				if (f.isDirectory()) {
					list.addAll(findFilesWithSubFolders(absolutePath, regexp));
				} else if (f.isFile()) {
					String filename = f.getName();
					Pattern pattern = Pattern.compile(regexp);
					Matcher matcher = pattern.matcher(filename);
					boolean matched = matcher.matches();
					if (matched) {
						list.add(absolutePath);
					}
				}
			}
		}
		return list;
	}

	public static boolean createFolder(String path) {
		File file = new File(path);
		if (file.exists()) {
			return true;
		}
		return file.mkdirs();
	}

	public String toString() {
		return "com.j3.file.FolderUtils , version 1.0, date 2007.03.14, author xiaodong";
	}
}
